package com.whz.workmanageol.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * 抽取出来的下载文件功能类
 */
public class DownloadFile {
    private static final Logger logger = LoggerFactory.getLogger(DownloadFile.class);
    // 缓冲数组大小10M
    private static final int MAX_BYTE = 10 * 1024 *1024;

    public static void download(InputStream is, HttpServletResponse response, String fileName) throws IOException{
        try (BufferedInputStream bis = new BufferedInputStream(is);
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())){
            int fileSize = bis.available();
            // 文件的总字节数
            long totalBytes = bis.available();
            // 拆分为数组后循环的次数
            int arrCount  = (int) Math.floor(totalBytes / MAX_BYTE);
            // 拆分数组后剩余的字节数
            int leaveSize = (int) (totalBytes % MAX_BYTE);
            byte[] buf;
            for(int i = 0; i < arrCount; i++) {
                buf = new byte[MAX_BYTE];
                bis.read(buf, 0, MAX_BYTE);
                bos.write(buf, 0, MAX_BYTE);
            }
            buf = new byte[leaveSize];
            bis.read(buf, 0, leaveSize);
            bos.write(buf, 0, leaveSize);
        }
        DownloadSet.setContent(response, fileName);
    }
}
